using System;
using System.IO.IsolatedStorage;
using System.Xml.Serialization;

namespace Life
{
    /// <summary>
    /// Basic file operations
    /// </summary>
    static class FileManager
    {
        public static void Save<T>(string fileName, T data)
        {
            IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();

            // open isolated storage, save file
            IsolatedStorageFileStream fs = null;
            using (fs = storage.CreateFile(fileName))
            {
                if (fs != null)
                {
                    // Convert the object to XML data and put it in the stream.
                    XmlSerializer serializer = new XmlSerializer(typeof(T));

                    serializer.Serialize(fs, data);
                }
            }
        }

        public static T Load<T>(string fileName)
            where T : class
        {
            T ret = null;

            // try to open isolated storage, and load data from the filename if it exists
            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (storage.FileExists(fileName))
                {
                    try
                    {
                        using (IsolatedStorageFileStream fs = storage.OpenFile(fileName, System.IO.FileMode.Open))
                        {
                            if (fs != null)
                            {
                                XmlSerializer serializer = new XmlSerializer(typeof(T));

                                ret = (T)serializer.Deserialize(fs);
                            }
                        }
                    }
                    catch (InvalidOperationException)
                    {
                        // TODO: Handle deserialization gracefully.  For example, don't display any malformed files.
                        storage.DeleteFile(fileName);
                    }
                }
            }

            return ret;
        }

        public static void Delete(string fileName)
        {
            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (storage.FileExists(fileName))
                {
                    storage.DeleteFile(fileName);
                }
            }
        }

        public static string[] GetFileNames(string searchPattern)
        {
            string[] fileNameList = new string[0];

            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                fileNameList = storage.GetFileNames(searchPattern);
            }
            return fileNameList;
        }
    }
}
